package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;

import io.minio.MinioClient;
import io.minio.MinioProperties;
import io.minio.errors.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Api(tags = "文件上传通用接口")
@Slf4j
public class CommonController {

    @Autowired
    AliOssUtil storageTemplate;

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        log.info("文件上传对象{}", file);
        //获得文件的名字
        try {
            //获得原始文件名
            String originalFilename = file.getOriginalFilename();
            //获得原始文件名字后缀
            String lastName = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构建新的文件名字
            String newName = UUID.randomUUID() + lastName;
//            //设置文件请求路径
            String upload = storageTemplate.upload(file.getBytes(),newName);

            return Result.success(upload);

        } catch (RuntimeException e) {
            log.error("文件上传失败{}", e);

        }

        return Result.error(MessageConstant.UPLOAD_FAILED);
    }

}